import React from "react";
import ReactDom from "react-dom";
import {combineReducers, applyMiddleware, compose} from "redux";
import thunkMiddleware from "redux-thunk/lib/index";
import {Provider} from "react-redux";
import {createHistory, useBasename, createHashHistory} from "history";
import Router from "react-router/lib/Router";
import Route from "react-router/lib/Route";
import useRouterHistory from "react-router/lib/useRouterHistory";
import syncHistoryWithStore from "react-router-redux/lib/sync";
import configureStore from "./store/configureStore";
import {routerReducer} from "react-router-redux/lib/reducer";
import objectAssign from 'object-assign'

import {WeaErrorPage} from "ecCom";
import weaFavourite from "./index";
import Home from "./containers/Home";
import {comsReducer} from "../coms/index";

const FavouriteRoute = weaFavourite.route;
const FavouriteAction = weaFavourite.action;
const FavouriteReducer = weaFavourite.reducers;


let reducers = objectAssign({}, FavouriteReducer, {routing: routerReducer});

const rootReducer = combineReducers({...reducers, ...comsReducer});
const debug = true;

let store = configureStore(
    rootReducer,
    applyMiddleware(
        thunkMiddleware
    )
);

if (debug && !(window.attachEvent && navigator.userAgent.indexOf('Opera') === -1) && window.__REDUX_DEVTOOLS_EXTENSION__) { //非IE才有debug
    store = configureStore(
        rootReducer,
        compose(
            applyMiddleware(
                thunkMiddleware
            ), window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
    )
}

var unsubscribe = store.subscribe(() => {
    /**console.log("listener...");
    console.log(store.getState());*/
});

const browserHistory = useRouterHistory(createHashHistory)({
    queryKey: '_key',
    basename: '/'
});

const history = syncHistoryWithStore(browserHistory, store);

class Error extends React.Component {
    render() {
        return (
            <WeaErrorPage msg="对不起，无法找到该页面！"/>
        )
    }
}

class NullPage extends React.Component {
    render() {
        return (
            <div></div>
        )
    }
}

class Root extends React.Component {
    render() {
        return (
            <Provider store={store}>
                <Router history={history}>
                    <Route path="/" component={NullPage}>
                    </Route>
                    <Route path="/main" component={Home}>
                        {FavouriteRoute}
                    </Route>
                    <Route path="*" component={Error}/>
                </Router>
            </Provider>
        )
    }
}

ReactDom.render(<Root/>, document.getElementById("container"));

unsubscribe();

